package com.farm.wcp.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.FarmAuthorityService;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
import com.farm.core.time.TimeTool;
import com.farm.project.domain.Company;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectType;
import com.farm.project.domain.Projectuser;
import com.farm.project.domain.ex.ProjectField;
import com.farm.project.service.CompanyServiceInter;
import com.farm.project.service.FieldServiceInter;
import com.farm.project.service.ProjectFieldinsServiceInter;
import com.farm.project.service.ProjectGradationServiceInter;
import com.farm.project.service.ProjectServiceInter;
import com.farm.project.service.ProjectTypeServiceInter;
import com.farm.project.service.ProjectcompanyServiceInter;
import com.farm.project.service.ProjectuserServiceInter;
import com.farm.project.service.TaskServiceInter;
import com.farm.project.service.TaskTypeServiceInter;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;

/**
 * 项目视图
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/workproject")
@Controller
public class WorkProjectWebController extends WebUtils {
	private static final Logger log = Logger.getLogger(WorkProjectWebController.class);
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private ProjectTypeServiceInter projectTypeServiceImpl;
	@Resource
	private ProjectGradationServiceInter projectGradationServiceImpl;
	@Resource
	private TaskServiceInter taskServiceImpl;
	@Resource
	private TaskTypeServiceInter taskTypeServiceImpl;
	@Resource
	private ProjectFieldinsServiceInter projectFieldinsServiceImpl;
	@Resource
	private FieldServiceInter fieldServiceImpl;
	@Resource
	private CompanyServiceInter companyServiceImpl;
	@Resource
	private ProjectcompanyServiceInter projectCompanyServiceImpl;
	@Resource
	private ProjectuserServiceInter projectUserServiceImpl;

	/***
	 * 項目屬性編輯窗口
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/fieldEditPage")
	public ModelAndView fieldEditPage(String projectId, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			// 获得任务项目名称
			Project project = projectServiceImpl.getProjectEntity(projectId);
			view.putAttr("project", project);
			LoginUser cuser = FarmAuthorityService.getInstance().getUserById(project.getCuser());
			view.putAttr("cuser", cuser);
			ProjectType projectType = projectTypeServiceImpl.getProjecttypeEntity(project.getTypeid());
			view.putAttr("projectType", projectType);
			return view.returnModelAndView("/web-simple/projectview/fieldEdit");
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/**
	 * 加载当前任务属性
	 * 
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadFieldWin")
	public ModelAndView loadTaskFieldWin(String projectId, HttpSession session) {
		try {
			List<ProjectField> fields = projectFieldinsServiceImpl.getAllProjectFields(projectId, null);
			ViewMode view = ViewMode.getInstance();
			view.putAttr("fields", fields);
			return view.returnModelAndView("/web-simple/worktask/commons/includeTaskFieldLoadBoxLoader");
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView("/web-simple/worktask/commons/includeTaskFieldLoadBoxLoader");
		}
	}

	/***
	 * 工作首页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		// 获取项目类型
		view.putAttr("types", projectTypeServiceImpl.getAllTypes("1"));
		// 获取时间年列表
		view.putAttr("years", TimeTool.getFirstYearList(5));
		view.putAttr("MODEL", "PROJECTVIEW");
		return view.returnModelAndView(ThemesUtil.getThemePage("plogs-webp-index", request));
	}

	/***
	 * 获取用户所有任务
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadProject")
	@ResponseBody
	public Map<String, Object> loadProject(String typeid, String year4, String name, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			DataQuery query = DataQuery.getInstance();
			if (StringUtils.isNotBlank(typeid)) {
				query.addRule(new DBRule("a.TYPEID", typeid, "="));
			}
			if (StringUtils.isNotBlank(year4)) {
				query.addRule(new DBRule("a.CTIME", year4, "like-"));
			}
			if (StringUtils.isNotBlank(name)) {
				DataQuerys.wipeVirus(name);
				query.addSqlRule(" and (a.NAME like '%" + name + "%' or d.name like '%" + name + "%')");
			}
			query.setPagesize(500);
			query.setNoCount();
			DataResult result = projectServiceImpl.getProjectsForManager(query, getCurrentUser(session));
			result.runformatTime("CTIME", "yyyy-MM-dd");
			view.putAttr("projects", result);
			return view.returnObjMode();
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/***
	 * 添加|修改项目表单
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadProjectFormWin")
	public ModelAndView loadProjectFormWin(String projectId, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			if (StringUtils.isNotBlank(projectId)) {
				// 修改,名称类型，阶段
				Project project = projectServiceImpl.getProjectEntity(projectId);
				ProjectType projectType = projectTypeServiceImpl.getProjecttypeEntity(project.getTypeid());
				view.putAttr("project", project);
				view.putAttr("projectType", projectType);
				view.putAttr("projectTypes", projectTypeServiceImpl.getAllTypes("1"));
				view.putAttr("gradations", projectGradationServiceImpl.getGradationsByTypeid(project.getTypeid()));
				view.putAttr("company", companyServiceImpl.getProjectCompany(project.getId()));
			} else {
				// 添加
			}
			view.putAttr("projectTypes", projectTypeServiceImpl.getAllTypes("1"));
			return view.returnModelAndView("/web-simple/workproject/commons/includeAddProjectWinLoader");
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView("/web-simple/workproject/commons/includeAddProjectWinLoader");
		}
	}

	/***
	 * 根据项目获取阶段列表
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadGradations")
	@ResponseBody
	public Map<String, Object> loadGradations(String projectTypeid, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			List<ProjectGradation> gradations = projectGradationServiceImpl.getGradationsByTypeid(projectTypeid);
			view.putAttr("gradations", gradations);
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/projectSubmit")
	@ResponseBody
	public Map<String, Object> projectSubmit(String id, String name, String gradationid, String typeid,
			String companyid, String companyname, String companytype, HttpSession session) {
		try {
			if (StringUtils.isNotBlank(companyid)) {
				// 修改机构
				Company company = companyServiceImpl.getCompanyEntity(companyid);
				company.setName(companyname);
				company.setType(companytype);
				companyServiceImpl.editCompanyEntity(company, getCurrentUser(session));
			} else {
				// 添加机构
				Company company = new Company();
				company.setName(companyname);
				company.setType(companytype);
				company = companyServiceImpl.insertCompanyEntity(company, getCurrentUser(session));
				companyid = company.getId();
			}
			ViewMode view = ViewMode.getInstance();
			Project project = null;
			if (StringUtils.isNotBlank(id)) {
				// 修改
				project = projectServiceImpl.getProjectEntity(id);
				project.setName(name);
				project.setGradationid(gradationid);
				project.setTypeid(typeid);
				project = projectServiceImpl.editProjectEntity(project, getCurrentUser(session));
			} else {
				// 添加
				project = new Project();
				project.setName(name);
				project.setGradationid(gradationid);
				project.setTypeid(typeid);
				project.setState("1");
				project = projectServiceImpl.insertProjectEntity(project, getCurrentUser(session));
				projectUserServiceImpl.resetProjectuser(project.getId(), getCurrentUser(session));
			}
			if (StringUtils.isNotBlank(id)) {
				projectServiceImpl.refreshLiveTime(id);
			}
			projectCompanyServiceImpl.bindProjectCompany(project.getId(), companyid);
			view.putAttr("project", project);
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/***
	 * 打开項目快捷菜单
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/openProjectMenuWin")
	public ModelAndView openProjectMenuWin(String projectid, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			Project project = projectServiceImpl.getProjectEntity(projectid);
			view.putAttr("project", project);
			Company company = companyServiceImpl.getProjectCompany(project.getId());
			view.putAttr("company", company);
			view.putAttr("type", projectTypeServiceImpl.getProjecttypeEntity(project.getTypeid()));
			view.putAttr("user", FarmAuthorityService.getInstance().getUserById(project.getCuser()));
			view.putAttr("usersize", projectUserServiceImpl.getProjectUsers(projectid).size());
			return view.returnModelAndView("/web-simple/workproject/commons/includeProjectMenuWinLoader");
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView("/web-simple/workproject/commons/includeProjectMenuWinLoader");
		}
	}

	/***
	 * 更新任務狀態
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/updateProjectState")
	@ResponseBody
	public Map<String, Object> updateProjectState(String projectid, String state, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			projectServiceImpl.editProjectState(projectid, state, getCurrentUser(session));
			return view.returnObjMode();
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 檢索已有项目机构
	 * 
	 * @param name
	 * @param session
	 * @return
	 */
	@RequestMapping("/queryCompany")
	@ResponseBody
	public Map<String, Object> queryCompany(String name, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			List<Company> companys = companyServiceImpl.findCompanys(name);
			view.putAttr("companys", companys);
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/***
	 * 添加|修改项目表单
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadProjectUsersFormWin")
	public ModelAndView loadProjectUsersFormWin(String projectId, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			view.putAttr("projectId", projectId);
			return view.returnModelAndView("/web-simple/workproject/commons/includeAddUserWinLoader");
		} catch (Exception e) {
			log.error(e);
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView("/web-simple/workproject/commons/includeAddUserWinLoader");
		}
	}

	/**
	 * 项目中加载所有人员
	 * 
	 * @param name
	 * @param session
	 * @return
	 */
	@RequestMapping("/queryAllUser")
	@ResponseBody
	public Map<String, Object> queryAllUser(String name, Integer page, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			if (page == null) {
				page = 1;
			}
			DataQuery query = DataQuery.getInstance(page,
					"a.NAME as USERNAME,a.ID as USERID,c.name as ORGNAME,A.LOGINNAME AS LOGINNAME",
					"ALONE_AUTH_USER A LEFT JOIN ALONE_AUTH_USERORG B ON B.USERID=A.ID LEFT JOIN ALONE_AUTH_ORGANIZATION C ON C.ID=B.ORGANIZATIONID");
			if (StringUtils.isNotBlank(name)) {
				query.addSqlRule("and (a.name like '%" + name + "%' or c.name like '%" + name + "%')");
			}
			query.addRule(new DBRule("A.STATE", "1", "="));
			query.setPagesize(10);
			view.putAttr("datas", query.search());
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 项目中加载所有人员
	 * 
	 * @param name
	 * @param session
	 * @return
	 */
	@RequestMapping("/queryProjectUser")
	@ResponseBody
	public Map<String, Object> queryProjectUser(String projectid, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			DataQuery query = projectUserServiceImpl.getProjectUsersQuery(projectid);
			view.putAttr("datas", query.search());
			DataResult result = query.search();
			result.runDictionary("1:管理员,2:成员", "POPTYPE");
			view.putAttr("datas", result);
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 添加人员到项目中
	 * 
	 * @param userid
	 * @param projectid
	 * @param poptype
	 * @param session
	 * @return
	 */
	@RequestMapping("/addUserToProject")
	@ResponseBody
	public Map<String, Object> addUserToProject(String userid, String projectid, String poptype, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			projectUserServiceImpl.adduser(projectid, userid, poptype, getCurrentUser(session));
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除人员从项目中
	 * 
	 * @param userid
	 * @param projectid
	 * @param poptype
	 * @param session
	 * @return
	 */
	@RequestMapping("/delUserToProject")
	@ResponseBody
	public Map<String, Object> delUserToProject(String projectUserId, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			projectUserServiceImpl.deleteProjectuserEntity(projectUserId, getCurrentUser(session));
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 变更用户权限
	 * 
	 * @param projectUserId
	 * @param session
	 * @return
	 */
	@RequestMapping("/editUserToProject")
	@ResponseBody
	public Map<String, Object> editUserToProject(String projectUserId, String poptype, HttpSession session) {
		try {
			ViewMode view = ViewMode.getInstance();
			Projectuser puser = projectUserServiceImpl.getProjectuserEntity(projectUserId);
			puser.setPoptype(poptype);
			projectUserServiceImpl.editProjectuserEntity(puser, getCurrentUser(session));
			return view.returnObjMode();
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

}